package cc.chinagps.gateway.mq.writer;

import cc.chinagps.gateway.buff.GBossDataBuff;
import cc.chinagps.gateway.common.Config;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Session;
import java.util.HashMap;
import java.util.Map;

public class MQWriter {
    private Map<String, IWriter> writerMap = new HashMap<>();
    private ConnectionFactory factory;

    private MQWriter() {
    }

    private static class SingletonHolder {
        private static final MQWriter INSTANCE = new MQWriter();
    }

    public static final MQWriter getInstance() {
        return MQWriter.SingletonHolder.INSTANCE;
    }

    public void init() throws Exception {
        factory = new ActiveMQConnectionFactory(Config.MQ.URL);
        Connection connection = openConnection();
        connection.start();
        Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);

        IWriter packetWriter = new EGPacketWriter(session);
        packetWriter.startService();
        writerMap.put(Config.MQ.EG_PACKET_NAME, packetWriter);

    }

    public Connection openConnection() throws Exception {
        return factory.createConnection();
    }

    public void addEGPacket(GBossDataBuff.EGPacketInfo packetInfo) {
        writerMap.get(Config.MQ.EG_PACKET_NAME).addData(packetInfo);
    }

}
